﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using OPM.Class;
using OPM.Models;
using OPM.ServiceOfficer;

namespace OPM.Controllers
{
    public class ComplaintController : Controller
    {
        // รับเรื่องราวร้องเรียน
        public ActionResult Index()
        {
            Priority();
            Secret();
            Severity();
            var model = new GetCase();
            model.date_opened = DateTime.Now;
            //var editCase = WSO.GetCase(U.Token, "099AAC5FBF4141C2905F1C1688FBBF68");
            //ViewBag.editCase = editCase;
            return View(model);
        }

        // รับเรื่องราวร้องเรียน (เซฟ โดยส่งมาจาก javascript)
        [HttpPost]
        public JsonResult InformCase(FormCollection f = null, string objective_id = null, string type_id = null,
            string terminal_type_id = null, string status_id = null,
            string date_opened = null, string date_closed = null, string channel_incoming_id = null,
            string call_back = null, string channel_outgoing_id = null,
            string summary = null, string detail = "", string defendent = "", string used_inform_with = null,
            string date_occurrenced_from = null, string date_occurrenced_to = null,
            string time_occurrenced = null, string country_id = null, string case_area = null,
            string subdistrict_id = null, string district_id = null, string province_id = null,
            string postcode = null, string latitude = null, string longitude = null, string case_value = null,
            string is_in_court = null, string remark = "", string is_secret = null, string priority_id = null,
            string severity_id = null,
            string secret_id = null, string org_master_id = "1", OPM.ServiceOfficer.ArrayOfString org_id = null,
            string cont_is_secret = null, string cont_type = null, string cont_gender_id = null,
            string cont_title = null,
            string cont_firstname = null, string cont_lastname = null, string cont_citizen_id = null,
            string cont_contact_detail = "", string cont_country_id = null, string cont_address = null,
            string cont_subdistrict_id = null, string cont_district_id = null, string cont_province_id = null,
            string cont_postcode = null, string cont_birthday = null, string cont_remark = "",
            int cont_number = 0, string cont_is_defective = null, string cont_is_victim = null, string cust_type = null,
            string cust_gender_id = null, string cust_title = null, string cust_firstname = null,
            string cust_lastname = null, string cust_citizen_id = null, string cust_contact_detail = "",
            string cust_country_id = null, int cust_number = 0, string cust_address = null,
            string cust_subdistrict_id = null, string cust_district_id = null, string cust_province_id = null,
            string cust_postcode = null, string cust_birthday = null, string cust_remark = "",
            string cust_is_defective = null, string cust_is_public = null, string reference = "",
            [Bind(Prefix = "file_name[]")] string[] file_name = null,
            [Bind(Prefix = "file_content[]")] string[] file_content = null,
            [Bind(Prefix = "file_description[]")] string[] file_description = null,
            [Bind(Prefix = "doc_type_id[]")] string[] doc_type_id = null,
            [Bind(Prefix = "doc_no[]")] string[] doc_no = null,
            [Bind(Prefix = "doc_date[]")] string[] doc_date = null,
            [Bind(Prefix = "doc_ref_no[]")] string[] doc_ref_no = null,
            [Bind(Prefix = "doc_ref_date[]")] string[] doc_ref_date = null,
            [Bind(Prefix = "doc_type[]")] string[] doc_type = null)
        {
            var formdata = UtilWeb.GetParamWithValueMvcFormCollection(f);
            string result1 = "";
            string case_id_result = "";
            bool foundError = false;
            ArrayOfString weekDays = new ArrayOfString {"110"};

            postcode = (postcode ?? "").PadRight(5, ' ').Substring(0, 5);
            cust_postcode = (cust_postcode ?? "").PadRight(5, ' ').Substring(0, 5); 

            try
            {
                result1 = WSO.InformCase(U.Token, objective_id, type_id, terminal_type_id, status_id,
                    date_opened, date_closed, channel_incoming_id, call_back,
                    channel_outgoing_id, summary, detail, defendent, used_inform_with,
                    date_occurrenced_from, date_occurrenced_to, time_occurrenced, country_id, case_area,
                    subdistrict_id, district_id, province_id, postcode,
                    latitude, longitude, case_value, is_in_court,
                    remark, is_secret, priority_id, severity_id,
                    secret_id, org_master_id, weekDays, cont_is_secret, cont_type,
                    cont_gender_id, cont_title, cont_firstname, cont_lastname,
                    cont_citizen_id, cont_contact_detail, cont_country_id, cont_address,
                    cont_subdistrict_id, cont_district_id, cont_province_id, cont_postcode,
                    cont_birthday, cont_remark, cont_number, cont_is_defective, cont_is_victim, cust_type,
                    cust_gender_id, cust_title, cust_firstname, cust_lastname,
                    cust_citizen_id, cust_contact_detail, cust_country_id, cust_number,
                    cust_address, cust_subdistrict_id, cust_district_id, cust_province_id,
                    cust_postcode, cust_birthday, cust_remark, cust_is_defective, cust_is_public);

                #region

                // Debug
                //foreach (var k in f.AllKeys)
                //{
                //    result1 += k + "=" + (f[k] == null ? "(NULL)" : f[k]) + "\r\n";
                //}  
                /*var result1 = WSO.InformCase(U.Token, objective_id, type_id, terminal_type_id, status_id,
                    date_opened, date_closed, channel_incoming_id, call_back,
                    channel_outgoing_id, summary, detail, defendent, used_inform_with,
                    date_occurrenced_from, date_occurrenced_to, time_occurrenced, country_id, case_area,
                    subdistrict_id, district_id, province_id, postcode,
                    latitude, longitude, case_value, is_in_court,
                    remark, is_secret, priority_id, severity_id,
                    secret_id, org_master_id, weekDays, cont_is_secret, cont_type,
                    cont_gender_id, cont_title, cont_firstname, cont_lastname,
                    cont_citizen_id, cont_contact_detail, cont_country_id, cont_address,
                    cont_subdistrict_id, cont_district_id, cont_province_id, cont_postcode,
                    cont_birthday, cont_remark, cont_number, cont_is_defective, cont_is_victim, cust_type,
                    cust_gender_id, cust_title, cust_firstname, cust_lastname,
                    cust_citizen_id, cust_contact_detail, cust_country_id, cust_number,
                    cust_address, cust_subdistrict_id, cust_district_id, cust_province_id,
                    cust_postcode, cust_birthday, cust_remark, cust_is_defective, cust_is_public);*/

                //var result1 = WSO.InformCase(U.Token, "8", "3", "", "13",
                //     "2015-05-01", "2015-05-01", "2", "F",
                //     "3", "xxxxx", "น้ำประปาสกปรก", "3", "312",
                //     "2015-05-01", "2015-05-31", "08:00", "BE99E1FA21F2B35B7FF90DB29616E596", "ถนนลาดพร้าว",
                //     "121801", "1233", "12", "10900",
                //     "8.0862997", "98.90628349999997", "0", "T",
                //     "ทดสอบ", "T", "1", "2",
                //     "3", "112", weekDays, "T", "C",
                //     "C833A9E6D354B2AC350A50CFB41852A8", "นาย", "สมศักดิ์", "สมบูรณ์",
                //     "11111111111", "021234567,023456789", "BE99E1FA21F2B35B7FF90DB29616E596", "ถนนลาดพร้าว",
                //     "121801", "1233", "12", "10900",
                //     "2015-05-01", "หมายเหตุ", 1, "F", "F", "C",
                //     "C833A9E6D354B2AC350A50CFB41852A8", "นาย", "aaa", "bbb",
                //     "22222222222", "021234567,023456789", "BE99E1FA21F2B35B7FF90DB29616E596", 1,
                //     "กรมศุลากร", "121801", "1233", "12", "10900", "", "เพื่อทดสอบ", "F", "F");

                #endregion

                // Result:นร580500000023|C38EF7CF861C4D088C96D6A1CD366ADB
                case_id_result = Util.TryCutString(result1, "|", 1).Replace("\"", "");
                string attachment_id = "";
                if (!string.IsNullOrWhiteSpace(case_id_result) && file_content != null && file_content.Any())
                {
                    for (int i = 0; i < file_content.Length; i++)
                    {
                        var file_content_type_ = file_content[i].Split(',')[0];
                        var file_content_base64_ = file_content[i].Split(',')[1];

                        var token = U.Token;
                        var file_name_ = ""; //file_name[i];
                        var file_content_ = file_content_base64_;
                        var file_description_ = file_description[i];
                        var doc_type_id_ = doc_type_id[i];
                        var doc_type_ = doc_type[i];
                        var doc_no_ = doc_no[i];
                        var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                        var doc_ref_no_ = doc_ref_no[i];
                        var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                        attachment_id += "รหัสเอกสารแนบ " + (i + 1) + ": " +
                                         WSO.InformAttachment(token, case_id_result, file_name_, file_content_,
                                             file_description_, doc_type_id_, doc_type_, doc_no_, doc_date_, doc_ref_no_,
                                             doc_ref_date_);
                    }
                }
            }
            catch (Exception ex)
            {
                foundError = true;
                result1 = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : null);
            }

            var result = new InformCaseSaveResult();
            var result_id = Util.TryCutString(result1, ":", 1).Replace("\"", "");

            if (string.IsNullOrWhiteSpace(case_id_result) || foundError)
            {
                result.successOrNot = false;
                result1 = "ผิดพลาด: " + (string.IsNullOrWhiteSpace(case_id_result) ? result1 : null);
                result.result_text = result_id;
            }
            else
            {
                result.successOrNot = true;
                result1 = "บันทึกสำเร็จ: " + result_id;
                result.result_text = case_id_result;
                result.case_id = case_id_result;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public class InformCaseSaveResult
        {
            public bool successOrNot { get; set; }
            public string case_id { get; set; }
            public string result_text { get; set; }
        }
        //วัตถุประสงค์การติดต่อ
        public ActionResult LovContactObj(string ref_val = "", bool isJson = false)
        {
            var listContaceObj = WSL.GetContactObjective(ref_val);
            if (isJson)
            {
                return Json(listContaceObj, JsonRequestBehavior.AllowGet);
            }
            return View(listContaceObj);
        }

        //วัตถุประสงค์ของการแจ้งเรื่อง
        public ActionResult LovCaseObjective()
        {
            var listCaseObjective = WSL.GetCaseObjective();
            return View(listCaseObjective);
        }

        //ช่องทางการติดต่อ
        public ActionResult LovChannelIn(string ref_val = "", bool isJson = false)
        {
            var listChanel = WSL.GetChannelIn(ref_val, U.org_id);
            if (isJson)
            {
                return Json(listChanel, JsonRequestBehavior.AllowGet);
            }
            return View(listChanel);

        }

        //ประเภทเรื่องร้องเรียน
        public ActionResult LovCaseType(string ref_val = "", bool isJson = false)
        {
            var listChanel = WSL.GetCaseType(ref_val);
            if (isJson)
            {
                return Json(listChanel, JsonRequestBehavior.AllowGet);
            }
            return View(listChanel);
        }

        //ประเภทเรื่องของหน่วยงาน
        public ActionResult LovCaseTerminalType(string ref_val = "", bool isJson = false)
        {
            var listOfCaseTerminalType = WSL.GetCaseTerminalType(U.org_id, ref_val);
            if (isJson)
            {
                return Json(listOfCaseTerminalType, JsonRequestBehavior.AllowGet);
            }
            return View(listOfCaseTerminalType);
            //var listOfCaseTerminalType = WSL.GetCaseTerminalType(U.org_id, ""); //("466", "466");
            //return View(listOfCaseTerminalType);
        }

        //เรียกข้อมูลหน่วยงาน
        public ActionResult LovOrganization2(string ref_val = "", bool isJson = false)
        {
            var listOfOrganization = WSL.GetOrganization(ref_val);
            if (isJson)
            {
                return Json(listOfOrganization, JsonRequestBehavior.AllowGet);
            }
            return View(listOfOrganization);
        }

        //เรียกข้อมูลหน่วยงาน
        public ActionResult LovOrganization()
        {
            var listOfOrganization = WSL.GetOrganization("");
            return View(listOfOrganization);
        }

        //หน่วยงานที่เกี่ยวข้อง
        [HttpGet]
        public ActionResult LovCaseTypeOrgOwne(string id)
        {
            var listCaseTypeOrgOwnen = WSL.GetCaseTypeOrgOwner(id);
            return View(listCaseTypeOrgOwnen);
        }

        //หน่วยงานที่เกี่ยวข้อง
        [HttpGet]
        public ActionResult LovCaseTypeOrgOwneUnderCaseType(string case_type_id)
        {
            if (string.IsNullOrWhiteSpace(case_type_id)) return Content("กรุณาเลือกประเภทเรื่องร้องเรียนก่อน");
            var listCaseTypeOrgOwnen = WSL.GetCaseTypeOrgOwner(case_type_id);
            return View("LovCaseTypeOrgOwne", listCaseTypeOrgOwnen);
        }

        //สถานะเรื่อง
        public ActionResult LovCaseStatus()
        {
            var listOfCaseStatus = WSL.GetCaseStatus();
            return View(listOfCaseStatus);
        }

        public ActionResult InformAttachment()
        {
            return View();
        }

        //ระดับชั้นความสำคัญ
        public void Priority()
        {
            var listOfPriority = WSL.GetPriority();
            ViewBag.listOfPriority = new SelectList(listOfPriority, "VAL", "TEXT");
        }

        //ระดับชั้นความลับ 
        public void Secret()
        {
            var listOfSecret = WSL.GetSecret();
            ViewBag.listOfSecret = new SelectList(listOfSecret, "VAL", "TEXT");
        }

        //ระดับชั้นความเร่งด่วน 
        public void Severity()
        {
            var listOfSeverity = WSL.GetSeverity();
            ViewBag.listOfSeverity = new SelectList(listOfSeverity, "VAL", "TEXT");
        }

        //ข้อมูลผู้ติดต่อ
        public ActionResult LovSearchContact()
        {
            var listOfSearchContact = WSO.SearchContactAccounts(U.Token, "", 0, 10);

            return View(listOfSearchContact);
        }

        public ActionResult PopupAddContact(string provinceId, string DistrictId)
        {
            LovGetCountry();
            GetProvinces();
            GetDistricts(provinceId);
            GetSubDistricts(DistrictId);
            GetGender();
            return View();
        }

        //เพศ
        public void GetGender()
        {
            var listOfGender = WSL.GetGender();
            ViewBag.listOfGender = new SelectList(listOfGender, "VAL", "TEXT");
        }

        public void LovGetCountry()
        {
            var listOfCountry = WSL.GetCountry();
            ViewBag.listOfCountry = new SelectList(listOfCountry, "VAL", "TEXT");
        }

        public void GetProvinces(string selectedProvinceId = null)
        {
            var listOfProvinces = WSL.GetProvinces();
            var listOfProvincesSl = new SelectList(listOfProvinces, "ID", "NAME");
            var selectedProvinceSl = listOfProvincesSl.FirstOrDefault(o => o.Value == selectedProvinceId);
            if (selectedProvinceSl != null)
            {
                selectedProvinceSl.Selected = true;
            }
            ViewBag.listOfProvinces = listOfProvincesSl;
        }

        public void GetDistricts(string provinceId, string selectedDistricteId = null)
        {
            var listOfDistricts = WSL.GetDistricts(provinceId);
            var listOfDistrictsSl = new SelectList(listOfDistricts, "ID", "NAME");
            var selectedDistrictSl = listOfDistrictsSl.FirstOrDefault(o => o.Value == selectedDistricteId);
            if (selectedDistrictSl != null)
            {
                selectedDistrictSl.Selected = true;
            }
            ViewBag.listOfDistricts = listOfDistrictsSl;
        }

        public void GetSubDistricts(string DistrictId, string selectedSubDistricteId = null)
        {
            var listOfSubDistricts = WSL.GetSubDistricts(DistrictId);
            var listSubOfDistrictsSl = new SelectList(listOfSubDistricts, "ID", "NAME");
            var selectedSubDistrictSl = listSubOfDistrictsSl.FirstOrDefault(o => o.Value == selectedSubDistricteId);
            if (selectedSubDistrictSl != null)
            {
                selectedSubDistrictSl.Selected = true;
            }
            ViewBag.listOfSubDistricts = listSubOfDistrictsSl;
        }

        public ActionResult GetDistrictsJson(string provinceId)
        {
            System.Threading.Thread.Sleep(200);
            var listOfDistricts = WSL.GetDistricts(provinceId);
            return Json(listOfDistricts, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetSubDistrictsJson(string districtId)
        {
            System.Threading.Thread.Sleep(200);
            var listOfSubDistricts = WSL.GetSubDistricts(districtId);
            return Json(listOfSubDistricts, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetCrime(string provinceId, string DistrictId, string SubDistrictId = null)
        {
            LovGetCountry();
            GetProvinces();
            GetDistricts(provinceId);
            GetSubDistricts(DistrictId);
            return View();
        }

        /// <summary>
        //ข้อมูลผู้เดือดร้อน
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult LovSearchCustomer()
        {
            var listOfSearchContact = WSO.SearchCustomerProfiles(U.Token, "", 0, 10);
            return View(listOfSearchContact);
        }

        public ActionResult PopupAddCustomer(string provinceId, string DistrictId)
        {
            LovGetCountry();
            GetGender();
            GetProvinces();
            GetDistricts(provinceId);
            GetSubDistricts(DistrictId);
            return View();
        }

        [HttpPost]
        public void AddNewContact(string cont_is_secret, string cont_type, string cont_gender_id, string cont_title,
            string cont_firstname, string cont_lastname, string cont_citizen_id, string cont_contact_detail,
            string cont_country_id, string cont_address, string cont_subdistrict_id, string cont_district_id,
            string cont_province_id, string cont_postcode, string cont_birthday, string cont_remark, int cont_number,
            string cont_is_defective, string cont_is_victim)
        {

        }

        public ActionResult ViewCaseDetail()
        {
            var editCase = WSO.GetCase(U.Token, "099AAC5FBF4141C2905F1C1688FBBF68");
            ViewBag.editCase = editCase;
            return View(editCase);
        }

        [HttpPost]
        public JsonResult GetCase(string token_id, string case_id)
        {
            return Json("", JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCaseById(string case_id)
        {
            return View("~/Views/Complaint/_Page5.cshtml", WSO.GetCase(U.Token, case_id));
        }
    }
}